//
//  CategoriesViewController.m
//  MemoryTasks
//
//  Created by Philippe Bouamriou on 12/05/10.
//  Copyright 2010 Philippe Bouamriou. All rights reserved.
//

#import "CategoriesViewController.h"
#import "MemoryTasksAppDelegate.h"
#import "CategoryEditionViewController.h"
#import "Category.h"


@implementation CategoriesViewController

@synthesize navController, categories, categoryTableView, parentCategory, viewMode, delegate, identifier;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
   
   if (viewMode == kCategoriesViewModeEdition) {
      UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] 
                                        initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                                        target:self 
                                        action:@selector(addButtonPressed)];
      
      self.navigationItem.rightBarButtonItem=barButtonItem;
   }
   
   
   if (parentCategory == nil) {
      self.title = NSLocalizedString(@"Categories", @"View title for category list");
   }
   else {
      self.title = parentCategory.name;
      self.navigationItem.prompt = NSLocalizedString(@"Sub Categories", @"View title for sub category list");
   }

   
   [self reloadDataWithTable:NO];
   [super viewDidLoad];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
   [super viewDidUnload];
   // Release any retained subviews of the main view.
   // e.g. self.myOutlet = nil;
   self.categories = nil;
   self.navController = nil;
   self.categoryTableView = nil;
}





#pragma mark -
#pragma mark Actions

- (IBAction)addButtonPressed {
   CategoryEditionViewController *categoryEditionViewCtrl = [[CategoryEditionViewController alloc] 
                                                             initWithNibName:@"CategoryEditionViewController" 
                                                             bundle:nil];
   categoryEditionViewCtrl.navController = navController;
   categoryEditionViewCtrl.parentCategory = parentCategory;
   [navController pushViewController:categoryEditionViewCtrl animated:YES];
   
}

#pragma mark -
#pragma mark Custom methods

- (void)reloadData {
   [self reloadDataWithTable:YES];
}

- (void)reloadDataWithTable:(BOOL)reloadTable {
   MemoryTasksAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
   NSManagedObjectContext *context = [appDelegate managedObjectContext];
   
   NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:context];
   NSFetchRequest *request = [[NSFetchRequest alloc] init];
   [request setEntity:entityDesc];
   
   NSError *error;
   NSArray *objects = [context executeFetchRequest:request error:&error];
   NSMutableArray *filteredCategories = [[NSMutableArray alloc] init];
   
   for( TaskCategory *category in objects) {
      if (category.parentCategory == parentCategory ) {
         [filteredCategories addObject:category];
      }
   }
   
   self.categories = [filteredCategories copy];
   
   if (reloadTable) {
      [categoryTableView reloadData];
   }
}

#pragma mark -
#pragma mark Implementation of protocol UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   return [categories count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
   static NSString *MyCell = @"MyCellCategory";
   
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyCell];
   
   if (cell == nil) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyCell];
   }
   
   cell.textLabel.text = [[categories objectAtIndex:indexPath.row] name];
   cell.detailTextLabel.text = [[categories objectAtIndex:indexPath.row] comment];
   if (parentCategory == nil && viewMode == kCategoriesViewModeEdition) {
      cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
   }
   else if (parentCategory != nil && viewMode == kCategoriesViewModeEdition) {
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
   }
   else {
      cell.accessoryType = UITableViewCellAccessoryNone;
   }


   
   return cell;   
}

#pragma mark -
#pragma mark Implementation of protocol UITableViewDelegate

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
   if (viewMode == kCategoriesViewModeEdition) {
      CategoryEditionViewController *categoryEditionViewCtrl = [[CategoryEditionViewController alloc] 
                                                                initWithNibName:@"CategoryEditionViewController" 
                                                                bundle:nil];
      categoryEditionViewCtrl.navController = navController;
      categoryEditionViewCtrl.categoryToModify = [categories objectAtIndex:indexPath.row];
      categoryEditionViewCtrl.parentCategory = parentCategory;
      [tableView deselectRowAtIndexPath:indexPath animated:YES];
      [navController pushViewController:categoryEditionViewCtrl animated:YES];
      
   }
   else {
      [delegate categoriesViewController:self didSelectCategory:[categories objectAtIndex:indexPath.row] 
                          withIdentifier:identifier];
   }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
        forRowAtIndexPath:(NSIndexPath *)indexPath {
   if (editingStyle == UITableViewCellEditingStyleDelete) {
      TaskCategory * category = [categories objectAtIndex:indexPath.row];
      MemoryTasksAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
      NSManagedObjectContext *context = [appDelegate managedObjectContext];
      [context deleteObject:category];
      NSError *error;
      if([context save:&error]) {
         [self reloadData];
      }
   }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
   CategoriesViewController *categoriesViewCtrl = [[CategoriesViewController alloc] 
                                                   initWithNibName:@"CategoriesViewController" 
                                                   bundle:nil];
   categoriesViewCtrl.navController = navController;
   categoriesViewCtrl.parentCategory = [categories objectAtIndex:indexPath.row];
   [navController pushViewController:categoriesViewCtrl animated:YES];
   
}


@end
